const path = require('path')
const webpack = require('webpack')
const GitRevisionPlugin = require('git-revision-webpack-plugin')
const GitRevision = new GitRevisionPlugin()
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const buildDate = JSON.stringify(new Date().toLocaleString())
const createThemeColorReplacerPlugin = require('./config/plugin.config')
const CompressionPlugin = require('compression-webpack-plugin')

function resolve (dir) {
  return path.join(__dirname, dir)
}
// add style resource
function addStyleResource (rule) {
  rule.use('style-resource')
    .loader('style-resources-loader')
    .options({
      patterns: [
        path.resolve(__dirname, './src/style/_var.less')
      ]
    })
}

// check Git
function getGitHash () {
  try {
    return GitRevision.version()
  } catch (e) {}
  return 'unknown'
}

const isProd = process.env.NODE_ENV === 'production'

const assetsCDN = {
  // webpack build externals
  externals: {
    vue: 'Vue',
    'vue-router': 'VueRouter',
    vuex: 'Vuex',
    axios: 'axios'
  },
  css: [],
  // https://unpkg.com/browse/vue@2.6.10/
  js: [
    './cdn/vue.min.js',
    './cdn/vue-router.min.js',
    './cdn/vuex.min.js',
    './cdn/axios.min.js'
  ]
}

// vue.config.js
const vueConfig = {
  publicPath: './',
  configureWebpack: {
    devtool: 'souce-map',
    // webpack plugins
    plugins: [
      // Ignore all locale files of moment.js
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
      // new webpack.DefinePlugin({
      //   APP_VERSION: `"${require('./package.json').version}"`,
      //   GIT_HASH: JSON.stringify(getGitHash()),
      //   BUILD_DATE: buildDate
      // }),
      createThemeColorReplacerPlugin()
    ],
    // if prod, add externals
    externals: isProd ? assetsCDN.externals : {}
  },

  chainWebpack: config => {
    config.resolve.alias.set('@', resolve('src'))

    const types = ['vue-modules', 'vue', 'normal-modules', 'normal']
        types.forEach(type =>
          addStyleResource(config.module.rule('less').oneOf(type))
        )

    const svgRule = config.module.rule('svg')
    svgRule.uses.clear()
    svgRule
      .oneOf('inline')
      .resourceQuery(/inline/)
      .use('vue-svg-icon-loader')
      .loader('vue-svg-icon-loader')
      .end()
      .end()
      .oneOf('external')
      .use('file-loader')
      .loader('file-loader')
      .options({
        name: 'assets/[name].[hash:8].[ext]',
        esModule: false
      })

    // if prod is on
    // assets require on cdn
    if (isProd) {
      config.plugin('CompressionPlugin')
        .use(new CompressionPlugin({
          filename: '[path][base].gz',
          algorithm: 'gzip',
          test: /\.js$|\.css$|\.html$/,
          threshold: 10240, // 只处理比这个值大的资源。按字节计算
          minRatio: 0.8 // 只有压缩率比这个值小的资源才会被处理
        }))
      config.plugin('html').tap(args => {
        args[0].cdn = assetsCDN
        return args
      })
    }
  },

  css: {
    loaderOptions: {
      less: {
        // modifyVars: {
        //   // less vars，customize ant design theme
        //   // 'primary-color': '#F5222D',
        // },
        // DO NOT REMOVE THIS LINE
        javascriptEnabled: true
      }
    }
  },

  devServer: {
    // development server port 8000
    port: 8000,
    // If you want to turn on the proxy, please remove the mockjs /src/main.jsL11
    // proxy: {
      // '/supermap': {
      //   target: 'https://iserver.supermap.io',
      //   ws: false,
      //   changeOrigin: true,
      //   pathRewrite: {
      //     '^/supermap': '' // 表示需要rewrite重写的
      //   }
      // }
    // }
  },

  // disable source map in production
  productionSourceMap: true,
  lintOnSave: false,
  // babel-loader no-ignore node_modules/*
  transpileDependencies: ['ol/renderer/webgl']
}
// 生产模式下分析打包大小
if (isProd) {
  // vueConfig.configureWebpack.plugins.push(
  //   new BundleAnalyzerPlugin({
  //     analyzerMode: 'static',
  //     //  在默认浏览器中自动打开报告
  //     openAnalyzer: true
  //   }))
}

module.exports = vueConfig
